package com.kangjia.model.m3.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kangjia.general.dao.query.OperType;
import com.kangjia.general.dao.query.Param;
import com.kangjia.general.dao.query.QueryParam;
import com.kangjia.general.service.AbstractService;
import com.kangjia.model.m3.dao.RelationDao;
import com.kangjia.model.m3.entity.IndexType;
import com.kangjia.model.m3.entity.Relation;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class RelationService extends AbstractService {

	@Autowired
	private RelationDao relationDao;
	
	public Relation get(Long relationId) {
		return relationDao.get(Relation.class, relationId);
	}

	public void delete(Long relationId) {
		relationDao.delete(Relation.class, relationId);
	}

	public void batchInsert(List<Relation> relations) {
		List<Relation> newList = new ArrayList<>();
		for (Relation relation : relations) {
			boolean is = count(relation) ? false : newList.add(relation);
			log.info("is={}", is);
		}
		if (!newList.isEmpty()) {
			relationDao.batch(newList);
		}
	}

	public List<IndexType> search(QueryParam queryParam) {
		List<IndexType> list = new ArrayList<>();
		List<Relation> relations = relationDao.query(Relation.class, queryParam);
		for (Relation relation : relations) {
			IndexType indexType = relationDao.get(IndexType.class, relation.getIndexTypeId());
			indexType.setRelationId(relation.getRelationId());
			list.add(indexType);
		}
		return list;
	}

	private boolean count(Relation relation) {
		QueryParam queryParam = new QueryParam();
		queryParam.addParam(new Param<Long>("indexTypeId", OperType.eq, relation.getIndexTypeId()));
		queryParam.addParam(new Param<Integer>("classify", OperType.eq, relation.getClassify()));
		queryParam.addParam(new Param<Integer>("inspectStandard", OperType.eq, relation.getInspectStandard()));
		queryParam.addParam(new Param<Integer>("targetId", OperType.eq, relation.getTargetId()));
		Integer count = relationDao.count(Relation.class, queryParam);
		if (count != null && count > 0) {
			return true;
		} else {
			return false;
		}
	}
}
